package com.example.hand.controller;


import com.example.hand.VO.ResultVO;
import com.example.hand.dataobject.CarBrand;
import com.example.hand.dto.BrandDTO;
import com.example.hand.service.BrandService;
import com.example.hand.utils.ResultVOUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/brand")
public class BrandController {


    @Autowired
    private BrandService brandService;


    @ApiOperation(value="添加车辆品牌", notes="添加车辆品牌")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "brandDTO", value = "品牌", required = true, dataType = "BrandDTO"),
    })
    @PostMapping("/create")
    public ResultVO create(@Valid BrandDTO brandDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new RuntimeException(bindingResult.getFieldError().getDefaultMessage());
        }

        ResultVOUtils resultVOUtils = new ResultVOUtils();
        CarBrand carBrand = new CarBrand();
        carBrand.setBrandName(brandDTO.getBrand_name());
        carBrand.setBrandPriority(brandDTO.getBrand_priority());
        CarBrand newCarBrand = brandService.add(carBrand);
        BrandDTO newBrandDTO = new BrandDTO(newCarBrand.getBrandId(),newCarBrand.getBrandName(),newCarBrand.getBrandPriority());
        return resultVOUtils.success(newBrandDTO);
    }

    @ApiOperation(value="删除车辆品牌", notes="车辆品牌")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "车辆品牌id", required = true, dataType = "Integer"),
    })
    @PostMapping("/delete")
    public ResultVO delete(@RequestParam("Id") Integer Id){
        brandService.deleteById(Id);
        ResultVOUtils resultVOUtils = new ResultVOUtils();
        return resultVOUtils.success();
    }

    @ApiOperation(value="车辆列表", notes="条件查询车辆列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "page", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "size", required = false, dataType = "Integer"),
    })
    @GetMapping("/list")
    public ResultVO list(@RequestParam(value = "page", defaultValue = "0") Integer page,
                         @RequestParam(value = "size", defaultValue = "10") Integer size)
    {
        PageRequest request = new PageRequest(page-1, size);
        ResultVOUtils resultVOUtils = new ResultVOUtils();
        Page<CarBrand> carBrands = brandService.findAll(request);
        return resultVOUtils.success(carBrands.getContent());

    }




}
